package wat.serwerapp.admins;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import wat.ziszcommon.invoker.Method;
import wat.serwerapp.usermgmt.ldap.RoleManager;
import wat.serwerapp.usermgmt.UserManager;
import wat.serwerapp.usermgmt.UserManager.User;

/**
 *
 * @author P.B. & L.G. & K.K.
 */
public class SetUsersList implements Method {

   private static Set<String> owners;

   public Set<String> getOwners() {
      if (owners == null) {
         owners = new HashSet<String>();
         owners.add("pl.edu.wat.erp.client.administration.UserAdministrationClient");
      }
      return owners;
   }

   // username:role,role,role;username:role,role
   public String invoke(String parameters) {
      try {
         String usersList = parameters;

         HashMap<String, Set<String>> users = new HashMap<String, Set<String>>();

         for (String userAndRoles : usersList.split(";")) {
            String[] user = userAndRoles.split(":");
            String userName = user[0];
            HashSet<String> rolesSet = new HashSet<String>();
            if (user.length == 2) {
               //posiada role
               String[] roles = user[1].split(",");
               for (String role : roles) {
                  rolesSet.add(RoleManager.roleToLdapFormat(role));
               }
            }
            users.put(userName, rolesSet);
         }

         Set<User> usrs = UserManager.getAllUsers();
         for (User user : usrs) {
            Set<String> roles = users.get(user.getName());
            user.setRoles(roles);
         }
         return "OK";
      } catch (NamingException ex) {
         Logger.getLogger(SetUsersList.class.getName()).log(Level.SEVERE, null, ex);
         return "NamingException";
      } catch (Exception ex) {
         Logger.getLogger(SetUsersList.class.getName()).log(Level.SEVERE, null, ex);
         return "Exception";
      }
   }

   public List invoke(List parameters) {
      throw new UnsupportedOperationException("Not supported yet.");
   }
}
